package gmongo

import (
	"errors"
	"reflect"

	"go.mongodb.org/mongo-driver/bson"
)

func RequiredCheck(fields []bson.M, data bson.M) error {
	for _, v := range fields {
		field := v["field"].(string)
		required := v["required"].(bool)
		value, ok := data[field]
		if !ok {
			if required {
				return errors.New(field)
			}
		} else {
			if required {
				if value == nil {
					return errors.New(field)
				}
				switch reflect.TypeOf(value).Name() {
				case "string":
					if value.(string) == "" {
						return errors.New(field)
					}
				case "int64":
					if value.(int64) == 0 {
						return errors.New(field)
					}
				case "float64":
					if value.(float64) == 0 {
						return errors.New(field)
					}
				}
			}
		}
	}
	return nil
}
